<?php
//error_reporting(E_ALL);

include_once('files/ftp.php');
include_once(STB_DIR.'/readFileSTB.php');
include_once(RASPONI_DIR.'/readFileRasponi.php');
include_once(SIMULAZIONI_DIR.'/readSimulazioni.php');
include_once(ALARM_FILE);

global $DATA_SCHEDULE,$DATA_SCHEDULE_SIMUL;
global $TEXT_STATUS_MSG;
$TEXT_STATUS_MSG='';
$DATA_SCHEDULE_SIMUL=strftime('%Y-%m-%d %H:%M:%S',time());
$NUM_TENT=10;

/*******************************************************************************
 * my_exec
 * execute command and return stdout stderr 
 ******************************************************************************/
function my_exec($cmd, $input='')
{
    global $TEXT_STATUS_MSG;
    $proc=proc_open($cmd, array(0=>array('pipe', 'r'), 1=>array('pipe', 'w'), 2=>array('pipe', 'w')), $pipes);
    fwrite($pipes[0], $input);fclose($pipes[0]);
    $stdout=stream_get_contents($pipes[1]);fclose($pipes[1]);
    $stderr=stream_get_contents($pipes[2]);fclose($pipes[2]);
    $rtn=proc_close($proc);
    if($rtn != 0)
    {
      $tmp=sprintf("\nCommando %s Stdout %s Stderr %s",$cmd,$stdout,$stderr);
      $TEXT_STATUS_MSG.=$tmp;
    }
    return array('stdout'=>$stdout,
               'stderr'=>$stderr,
               'return'=>$rtn
              );
} 

/*******************************************************************************
 * read_dir
 * read directory and return a list files of dir
 ******************************************************************************/
function read_dir($dir, $array = array()){ 
	if ($handle = opendir($dir)) {
		$files = array();
		while (false !== ($file = readdir($handle))) 
                {
		  if ($file != '.' && $file != '..') 
                      if(preg_match('/[0-9]{1,}-[0-9]{1,}-[0-9]{4}\.xls/',$file))
                              $files[] = $file;
		  
		}
                
	}
	return $files; 
}

/*******************************************************************************
 * textStatus
 * Insert Text status msg in DB that send message by email,sms,fax
 ******************************************************************************/
function textStatus()
{
    global $TEXT_STATUS_MSG,$DATA_SCHEDULE_SIMUL;
    if(! empty($TEXT_STATUS_MSG))
    {
        $msql  = new Db;
        $msql->connect();
        $msql->execute("INSERT INTO alarm_status (data,text) values ('$DATA_SCHEDULE_SIMUL','$TEXT_STATUS_MSG');");
        $msql->disconnettiDB();
    }
}  

/*******************************************************************************
 * last date processing file
 ******************************************************************************/
$msql  = new Db;
$msql->connect();
$arr_data=$msql->execute_select("SELECT data FROM dati_impianto order by data desc limit 1;");
$lastDataprocess=strtotime( $arr_data[0][0] );
$msql->disconnettiDB();
echo "$lastDataprocess----------\n";
$data_sec=strftime('%Y-%m-%d %H:%M:%S',$lastDataprocess);
echo "$data_sec----------\n";

$DATA_SCHEDULE="$data_sec";
echo $DATA_SCHEDULE;

/*******************************************************************************
 * Get IP of FTP servers
 ******************************************************************************/
$msql->connect();
$ftp_stb_arr=$msql->execute_select("SELECT ftp_ip,ftp_user,ftp_password FROM ftp_table where ftp_name='ftp_STB'");
$ftp_progea_arr=$msql->execute_select("SELECT ftp_ip,ftp_user,ftp_password FROM ftp_table where ftp_name='ftp_Progea'");
print_r($ftp_progea_arr);
$ftp_ip_stb=$ftp_stb_arr[0][0] ;
$ftp_user_stb= $ftp_stb_arr[0][1] ;
$ftp_password_stb=$ftp_stb_arr[0][2] ;

$ftp_ip_progea=$ftp_progea_arr[0][0] ;
$ftp_user_progea= $ftp_progea_arr[0][1] ;
$ftp_password_progea=$ftp_progea_arr[0][2] ;

$msql->disconnettiDB();


/*
 * Download Ultimo File da ftp STB 
 */
    //    for ($i=0;$i<=$NUM_TENT;$i++)
    //    {
    //        $arr=my_exec(CMD_VPN_UP);
    //
    //        print("$i: ".$arr['stdout']."\n");
    //        if(preg_match('/^Another.*/', $arr['stdout']))
    //        {
    //            echo "Connected VPN\n";
    //            break;
    //        }
    //        else if($i == $NUM_TENT)
    //        {
    //            $tringa_arr=my_exec("cat ".SNXRC_WORK);
    //            $tmp=sprintf("Impossibile connettersi alla VPN: %s",$tringa_arr['stdout']);
    //            $TEXT_STATUS_MSG.=$tmp;
    //        }
    //    }
    //
    //    $conn=new Ftp($ftp_ip_stb,$ftp_user_stb,$ftp_password_stb);
    //    if(!$conn->connetti_ftp(true))
    //    {
    //       $tmp=sprintf("\nImpossibile connettersi al server: %s. Controllare User %s e Password %s",$ftp_ip_stb,$ftp_user_stb,$ftp_password_stb);
    //       $TEXT_STATUS_MSG.=$tmp;
    //
    //       $log=new FileLog();
    //       $log->writeLog("main FTP not connect server:".$tmp);
    //       $log->close();  
    //    }
    //    $files_FTP=$conn->getLastFilesCreate(FTP_PATH_FILE,$lastDataprocess);
    //    print_r($files_FTP."----".count($files_FTP));

/*******************************************************************************
 * read file dati_impianto_ravenna_mm_gg_yyyy
 ******************************************************************************/
$ftp_rawlist=read_dir(STB_DIR);
$num_file=count($ftp_rawlist);

$files_FTP=$ftp_rawlist;
print_r($files_FTP."----".count($files_FTP));

foreach($files_FTP as $key => $v)
{
   $file=$files_FTP[$key];
    $data=$key;

   //prelevo file
   print $file." ".$data."\n";

//       $conn->getFile(STB_DIR."$file", "/".FTP_PATH_FILE."/$file");


   /* 
    * Read File STB
    */
    parserStbFile();
    echo $DATA_SCHEDULE;
    unlink( STB_DIR."$file");
}

//system(CMD_VPN_DOWN); 
$msql  = new Db;
$msql->connect();
$arr_data=$msql->execute_select("SELECT data FROM dati_impianto order by data desc limit 1;");
$lastDataprocessInsert=strtotime( $arr_data[0][0] );
$msql->disconnettiDB();
echo "$lastDataprocessInsert----------\n";
$data_sec=strftime('%Y-%m-%d %H:%M:%S',$lastDataprocessInsert);
echo "$data_sec----------\n";

$delta_time=$DATA_SCHEDULE_SIMU_SEC - $lastDataprocessInsert;
$DELTA_TIME_ORA=5400; // 1 ora
if($delta_time > $DELTA_TIME_ORA ) //ora
{
   $tmp="\nNon sono presenti file inviati dal server STB: $ftp_ip_stb. Ultimi dati ricevuti il $data_sec";
   $TEXT_STATUS_MSG.=$tmp;
}

/*******************************************************************************
 * Download Monitor.ARJ Progea
 ******************************************************************************/
$conn=new Ftp($ftp_ip_progea,$ftp_user_progea,$ftp_password_progea);
if($conn->connetti_ftp(true))
{
    $file=$conn->getNameFileType("arj");
    $conn->getFile(PATH_TEMPO_REALE."/$file",$file);
    $conn->disconnetti_ftp($conn->conn_id);

    chdir(PATH_TEMPO_REALE);
    system("arj e *.ARJ \"-ht".PATH_TEMPO_REALE."/dati_fiumi\" -y",$ret);
    system("rm -rf ".PATH_TEMPO_REALE."/dati_fiumi/*.ARJ; rm -rf ".PATH_TEMPO_REALE."*.ARJ",$status);
    my_exec("bash ".PATH_TEMPO_REALE."/programmi/esegui.bash",$ret);
    system("mv ".PATH_TEMPO_REALE."/storico_risultati_previsione/risultati_* ".SIMULAZIONI_DIR);
    system("cp ".PATH_TEMPO_REALE."/simulazioni.txt ".SIMULAZIONI_DIR);
    system("cp ".PATH_TEMPO_REALE."/H_Rasponi.txt ".RASPONI_DIR);
    $DATA_SCHEDULE_SIMUL=date("Y-m-d G:i:00");
    
     deleteOldDati();
    /*
    * Read File Rasponi
    */
    parserRasponi();

    /*
    * Read File Simulazioni
    */
    parserSimulazioni();
    parserFlagSimulazioni();
}
else
{
   $tmp=sprintf("Impossibile connettersi al server: %s. Controllare User e Password",$ftp_ip_progea);
   $TEXT_STATUS_MSG.=$tmp;
   
   $log=new FileLog();
   $log->writeLog("main FTP not connect server:".FTP_SERVER);
   $log->close();
}
$conn->disconnetti_ftp();


/*******************************************************************************
 * textStatus
 ******************************************************************************/
textStatus();


/*******************************************************************************
 * management Alarm
 ******************************************************************************/
$alarm=new Alarm();
$alarm->getSogliePresoglie();
 //check trasmission signal of channel 1 o 2 o 0
$alarm->checkTrasmission1o2o0();
 //check threshold of channel piezometro
$alarm->sogliaAllarme();
 //check threshold pre Alarm of channel piezometro
$alarm->sogliaAllarmPre();
$alarm->checkflagSimulazioniAllarm();
$return=$alarm->SendTrasmissionAlarm($alarm->SMS);
$return=$alarm->SendTrasmissionAlarm($alarm->FAX);
$return=$alarm->SendTrasmissionAlarm($alarm->EMAIL);
$alarm->SendPresogliaSogliaAlarm($alarm->SMS);
$alarm->SendPresogliaSogliaAlarm($alarm->FAX);
$alarm->SendPresogliaSogliaAlarm($alarm->EMAIL);
$alarm->SendPresogliaSogliaPrevAlarm($alarm->SMS);
$alarm->SendPresogliaSogliaPrevAlarm($alarm->FAX);
$alarm->SendPresogliaSogliaPrevAlarm($alarm->EMAIL);
$alarm->SendModelliPrevisioni($alarm->SMS);
$alarm->SendModelliPrevisioni($alarm->FAX);
$alarm->SendModelliPrevisioni($alarm->EMAIL);

getDay($DATA_SCHEDULE);

?>

